package com.exp.base.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.util.Assert;

/**
 * Cookie工具类
 * @author ThinkGem
 * @version 2013-01-15
 */
public class CookieUtils {

	public static class Option{
		public int expires=-1;
		public String path;
		public String domain;
		public boolean secure;
	}
	
	/**
	 * 设置cookie
	 * @param response
	 * @param name
	 * @param value
	 * @param option 为空时为默认值
	 */
	public static void add(HttpServletResponse response, String name, String value,Option option) {
		Assert.notNull(response, "response 不能为空");
		Assert.notNull(name, "name 不能为空");
		if(option==null){
			option = new Option();
		}
		Cookie cookie = new Cookie(name, null);
		cookie.setPath(StringUtils.defaultIfBlank(option.path, "/"));
		cookie.setMaxAge(option.expires);
		cookie.setDomain(StringUtils.defaultIfBlank(option.path, ""));
		cookie.setSecure(option.secure);
		try {
			cookie.setValue(URLEncoder.encode(value, "utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		response.addCookie(cookie);
	}
	
	/**
	 * 获得cookie值
	 * @param request
	 * @param name
	 * @return
	 */
	public static String get(HttpServletRequest request,String name) {
		Assert.notNull(request, "request 不能为空");
		Assert.notNull(name, "name 不能为空");
		String value = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					try {
						value = URLDecoder.decode(cookie.getValue(), "utf-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return value;
	}
	
	/**
	 * 删除指定的cookie
	 * @param request
	 * @param response
	 * @param name
	 */
	public static void remove(HttpServletRequest request, HttpServletResponse response, String name) {
		Assert.notNull(request, "request 不能为空");
		Assert.notNull(response, "response 不能为空");
		Assert.notNull(name, "name 不能为空");
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					cookie.setMaxAge(0);
					response.addCookie(cookie);
				}
			}
		}
	}
}
